import androidx.compose.foundation.layout.Row
import androidx.compose.foundation.layout.fillMaxSize
import androidx.compose.foundation.window.WindowDraggableArea
import androidx.compose.material.MaterialTheme
import androidx.compose.material.Surface
import androidx.compose.runtime.Composable
import androidx.compose.runtime.CompositionLocalProvider
import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.remember
import androidx.compose.runtime.setValue
import androidx.compose.ui.Alignment
import androidx.compose.ui.Modifier
import androidx.compose.ui.draw.clip
import androidx.compose.ui.res.painterResource
import androidx.compose.ui.unit.DpSize
import androidx.compose.ui.unit.dp
import androidx.compose.ui.window.FrameWindowScope
import androidx.compose.ui.window.Window
import androidx.compose.ui.window.WindowPosition
import androidx.compose.ui.window.application
import androidx.compose.ui.window.rememberWindowState
import icu.twtool.ui.component.ConfirmDialog
import icu.twtool.ui.router.rememberRouteState
import icu.twtool.ui.style.MyColors
import icu.twtool.ui.style.MyShape
import icu.twtool.ui.view.LeftView
import icu.twtool.ui.view.RightView
import icu.twtool.util.LocalRouteState

/**
 * Compose GUI 主入口
 */
@Composable
@Suppress("FunctionName")
fun FrameWindowScope.App(onCloseRequest: () -> Unit = {}) {
    MaterialTheme {
        WindowDraggableArea {
            Surface(
                modifier = Modifier.clip(MyShape.RoundedCornerLarge).fillMaxSize(),
                color = MyColors.PrimaryBackground,
                contentColor = MyColors.OnPrimaryBackground
            ) {
                val routeState = rememberRouteState()
                CompositionLocalProvider(LocalRouteState provides routeState) {
                    Row {
                        LeftView(routeState, onCloseRequest)
                        RightView(routeState)
                    }
                }
            }
        }
    }
}

/**
 * 主程序入口
 */
fun main() = application {
    val logoIcon = painterResource("icons/logo.svg")
    // 启动居中
    val windowState = rememberWindowState(position = WindowPosition(Alignment.Center), size = DpSize(1200.dp, 700.dp))
    var exitDialog by remember { mutableStateOf(false) }
    val exitHandler = {
        exitDialog = true
    }
    val closeDialog = {
        exitDialog = false
    }
    Window(
        onCloseRequest = exitHandler,
        resizable = false,      // 不可修改窗口大小
        state = windowState,    // 设置窗口的状态，默认启动居中
        title = "二元练习系统",   // 设置窗口的标题，虽然关闭了装饰器，但是会显示在任务栏
        icon = logoIcon,        // 设置窗口的图标，虽然关闭了装饰器，但是会显示在任务栏
        undecorated = true,     // 关闭默认装饰器
        transparent = true,     // 使窗口背景透明
    ) {
        App(onCloseRequest = exitHandler)
        if (exitDialog) {
            ConfirmDialog("确认退出?", "Tips: 点击确定将退出程序", onCloseRequest = closeDialog) {
                exitApplication()
            }
        }
    }
}